import React, { memo,useState,useEffect,useRef } from 'react'
import { useSelector } from "react-redux";
import { Button, Card,Form,Input,message,Select } from 'antd';
import { ArrowLeftOutlined ,MoneyCollectOutlined} from "@ant-design/icons";
import { reqCategoryList ,reqAddProduct} from "@/network";
import HjPicturesWall from "@/components/picture-wall";
import HjRichTextEditor from "@/components/rich-text-editor"

import { AddUpdateWrapper } from "./style";
const { Option } = Select;

export default memo(function HjAddUpdate(props) {


  // state props
  const productId = props.match.params.id
   const [cateList, setCateList] = useState([]);//将分类数据保存到组件中
   const [currentProduct, setCurrentProduct] = useState({});//将当前商品数据保存到组件中
   const [name, setName] = useState('name');//将当前商品数据保存到组件中

  // redux hooks
  const {categoryList,productList} = useSelector(state => ({
    categoryList:state.cate.categoryList,
    productList:state.product.productList
  }))

  //  other hooks
  const PicturesWallRef = useRef()
  const RichTextRef = useRef()
  const FormRef = useRef()


  // 修改操作类型(update，add)以及如果是更新商品那就从redux中获取对应的商品数据
  useEffect(() => {
      // 通过find方法将redux中的当前商品数据保存到组件中 (将当前的商品数据保存到组件中)
      if(productList.length){
        const currentProduct =  productList.find(item=>{
            return item._id===productId
          })
        if(currentProduct){
          setCurrentProduct(currentProduct)
          setName(currentProduct.name)
        }
      }
      console.log(1); 
    }, [productId,productList]);
    // setName(currentProduct.name)
  useEffect(() => {
    if(categoryList.length)setCateList(categoryList)
    else{
      // 发请求拿数据
      getCategoryList()
    }
    console.log(2);
    FormRef.current.resetFields()
  }, [categoryList]);

  
console.log(name);
  // handle function
  // 发请求拿数据
    const getCategoryList = async()=>{
      const result = await reqCategoryList()
       if(result.status ===0){
            setCateList(result.data)
       }
      }
      //请求添加商品
    const getAddProduct = async(productObj)=>{
        const result = await reqAddProduct(productObj)
        const {status} = result
        if(status===1) message.error('添加商品失败')
        else{
          props.history.replace('/admin/prod/product')
          message.success('添加商品成功')
        }
    }

    const submitValue = (value)=>{
      // 图片数组
      const imgs = PicturesWallRef.current.getImgArr()
      // 富文本内容数据
      const  detail = RichTextRef.current.getRichTxetValue()
      const submitvalue = {...value,imgs,detail}
      // 拿到完成的数据后就发请求添加商品
      getAddProduct(submitvalue)

    }
  return (
    <AddUpdateWrapper>
      <Card 
          title={
                 <div className="title">
                   <Button type="link"  icon={<ArrowLeftOutlined />} onClick={()=>{props.history.goBack()}}/>
                    <h3>{productId?'商品修改':'商品管理'}</h3>
                 </div>
           }
      >
           <Form
                name="basic"
                autoComplete="off"
                labelCol={{md:2}}
                wrapperCol={{md:8}}
                onFinish={submitValue}
                ref={FormRef}
                
              >
                <Form.Item
                  label="商品名称"
                  name="name"
                  initialValue={name||''}
                  rules={[
                    {
                      required: true,
                      message: '请输入商品名称',
                    },
                  ]}
                >
                  <Input  placeholder="商品名称"/>
               </Form.Item>
                <Form.Item
                  label="商品描述"
                  name="desc"
                  initialValue={currentProduct.desc ||''}
                  rules={[
                    {
                      required: true,
                      message: '请输入商品描述',
                    },
                  ]}
                >
                  <Input  placeholder="商品描述"/>
                </Form.Item>
                <Form.Item
                  label="商品价格"
                  name="price"
                  initialValue={currentProduct.price ||''}
                  rules={[
                    {
                      required: true,
                      message: '请输入价格',
                    },
                  ]}
                >
                  <Input  placeholder="商品价格" prefix={<MoneyCollectOutlined />} addonAfter="元" type="number"/>
                </Form.Item>
                <Form.Item
                  label="商品分类"
                  name="categoryId"
                  initialValue={currentProduct.categoryId ||''}
                >
                    <Select >
                      {cateList.map(cate => (
                        <Option key={cate._id} >{cate.name}</Option>
                      ))}
                    </Select>
                </Form.Item>
                <Form.Item
                  label="商品图片"
                  name="imgs"
                  initialValue={currentProduct.imgs ||''}
                >
                   <HjPicturesWall ref={PicturesWallRef}/>
                </Form.Item>
                <Form.Item
                  label="商品详情"
                  name="detail"
                  initialValue={currentProduct.detail ||''}
                >
                  <HjRichTextEditor ref={RichTextRef}/>
                </Form.Item>
                <Form.Item
                >
                    <Button type="primary" htmlType="submit">
                    提交
                  </Button>
                </Form.Item>
            </Form>
    </Card>
    </AddUpdateWrapper>
  )
})
